package com.zjmcollege.hotpot.controller;

import com.alibaba.fastjson.JSON;
import com.zjmcollege.hotpot.model.MsgModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-12 19:45
 */
@Controller
@RequestMapping("/community/chat")
@Slf4j
public class ChatController {
    // https://www.sohu.com/a/239587548_100192143
    public static List<String> nicknames = Arrays.asList(
            "鸿钧老祖", "太上老君", "元始天尊", "通天教主", "接引道人",
            "准提道人", "女娲娘娘", "陆压道人", "燃灯道人", "南极仙翁",
            "广成子",   "赤精子",   "玉鼎真人", "惧留孙",   "云中子",
            "道行天尊", "慈航道人", "黄龙真人", "灵宝大法师", "清虚道德真君",
            "普贤真人", "太乙真人", "文殊广法天尊", "姜子牙", "申公豹",
            "多宝道人", "无当圣母", "金灵圣母", "龟灵圣母", "乌云仙",
            "余元", "云霄", "火灵圣母", "菡芝仙", "石矶娘娘", "琼宵",
            "碧霄", "赵公明", "灵牙仙", "罗宣", "吕岳", "金光仙", "羽翼仙",
            "魔礼寿", "魔礼海", "魔礼红", "魔礼青", "杨森", "高友乾",
            "李兴霸", "王魔", "杨戬", "殷郊", "殷洪", "韦护", "杨任", "雷震子");

    /**
     * 根据局域网请求的host,对客户端用户取nickname
     */
    public static Map<String, MsgModel> userInfos = new HashMap();

    @Autowired
    private Environment env;

    @GetMapping
    public String chatPage(HttpServletRequest req,
                           HttpServletResponse resp,
                           Model model) throws UnknownHostException {
        String host = req.getRemoteHost();
        MsgModel userInfo = userInfos.get(host);

        if (userInfo == null) {
            userInfo = new MsgModel(nicknames.get(userInfos.size()),
                    host, "/chat/avatar/h" + ((userInfos.size() + 1) % 15) + ".png", null);

            userInfos.put(host, userInfo);
        }

        // 将分配的 nickname 放入到 cookie 中
        try {
            Cookie cookie = new Cookie("nickname",
                    URLEncoder.encode(userInfo.getNickname(), "utf-8"));
            resp.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        model.addAttribute("avatar", userInfo.getAvatar());
        model.addAttribute("nickname", userInfo.getNickname());
        String serverAddress = null;
        if (env.getProperty("server.address") == null) {
            InetAddress inetAddress = InetAddress.getLocalHost();
            serverAddress = inetAddress.getHostAddress();
        }
        model.addAttribute("server_address", serverAddress);
        model.addAttribute("server_port", env.getProperty("server.port"));
        return "chat/index";
    }

    @PostMapping
    @ResponseBody
    public void broadcast(@RequestBody String message,
                          HttpServletRequest req) {
        log.info("来自客户端的消息：{}", message);

        HashMap<Object, Object> result = new HashMap<>();
        result.put("type", ChatServerEndpoint.USER_SEND_MSG);

        MsgModel mm = userInfos.get(req.getRemoteHost());
        mm.setMsg(JSON.parseObject(message, MsgModel.class).getMsg());

        result.put("content", mm);
        try {
            ChatServerEndpoint.BroadCastInfo(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error("[web socket 消息分发失败]", e);
            e.printStackTrace();
        }
    }
}
